package hhh.babysleep.presenter.base;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;

import com.litesuits.common.assist.Toastor;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import hhh.babysleep.presenter.module.MainActivity;
import hhh.babysleep.presenter.MyApp;

/**
 * Created by hhh on 2017/6/12.
 */
public abstract class BaseActivity extends AppCompatActivity {
    protected String TAG;

    private boolean isExit=false;
    private Handler handler=new Handler();
    private Unbinder unbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        unbinder= ButterKnife.bind(this);
        MyApp.getApp().put(getClass().getName(),this);
        TAG=getClass().getName();
        initData();
    }

    protected abstract void initData();

    protected void addFragment(Fragment fragment){
        if(fragment!=null){
            getSupportFragmentManager().beginTransaction()
                    .replace(getFragmentContentId(),fragment,fragment.getClass().getSimpleName())
                    .addToBackStack(fragment.getClass().getSimpleName())
                    .commitAllowingStateLoss();
        }
    }

    protected void removeFragment(){
        if(getSupportFragmentManager().getBackStackEntryCount()>1){
            getSupportFragmentManager().popBackStack();
        }else{
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(getClass().getName().equals(MainActivity.class.getName())){
                if(isExit){

                }else{
                    isExit=true;
                    new Toastor(this).showToast("再按一次退出");
                    handler.postDelayed(r,2000);
                }
            }
//            if(getSupportFragmentManager().getBackStackEntryCount()==1){
//                finish();
//                return true;
//            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private Runnable r=new Runnable() {
        @Override
        public void run() {
            isExit=false;
        }
    };

    protected abstract int getFragmentContentId();
    protected abstract int getContentViewId();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        MyApp.getApp().remove(getClass().getName());
    }
}
